﻿Option Explicit On
Imports System.Data
Imports System.Xml
Imports System.IO
Imports System.Reflection
Imports System.Security.AccessControl
Imports System.ComponentModel
Imports CRM.BusinessLayer


Partial Public Class ReportCriteria

    Public Enum DateRanges
        All = 1
        Today = 2
        Select_Date = 3
        Select_Range = 4
        This_Week = 5
        Last_Week = 7
        This_Month = 6
        Last_Month = 8
        Yesterday = 9
        This_Month_Last_Year = 10
        Last_Month_Last_Year = 11
        Year_To_Date = 12
        Last_Year = 13
        Financial_Year_To_Date = 14
        Last_Financial_Year = 15
        From_Date_To_Present = 16
    End Enum

    Private Enum ProductSelection
        All = 1
        By_Department = 2
        Retired_Products = 3
        By_Product_Type = 4
    End Enum

    Private Enum Pageselection
        CrystalPage = 1
        GridPage = 2
    End Enum

    Private WriteOnly Property CurrentReport() As Reports.ReportType
        Set(ByVal value As Reports.ReportType)
            My.Settings.CurrentReport = value
            My.Settings.Save()
        End Set
    End Property

    Private WriteOnly Property ReportCriteria() As Reports.ReportCriteria
        Set(ByVal Value As Reports.ReportCriteria)
            'My.Settings.ReportCriteria = CType(Value, Object)
            'My.Settings.Save()
            GlobalCRM.ReportCriteriaNew = Value
        End Set
    End Property

    Private _currentRole As Integer
    Public Property CurrentRole() As Integer
        Get
            Return _currentRole
        End Get
        Set(ByVal value As Integer)
            _currentRole = value
        End Set
    End Property

    Private _ProductSelection As Integer
    Public Property Products() As Integer
        Get
            Return _ProductSelection
        End Get
        Set(ByVal value As Integer)
            _ProductSelection = value
        End Set
    End Property

    Private _SelectedReportIndex As Integer
    Public Property SelectedReportIndex() As Integer
        Get
            Return _SelectedReportIndex
        End Get
        Set(ByVal value As Integer)
            _SelectedReportIndex = value
        End Set
    End Property
    Private _SelectedReportName As String
    Public Property SelectedReportName() As String
        Get
            Return _SelectedReportName
        End Get
        Set(ByVal value As String)
            _SelectedReportName = value
        End Set
    End Property

    Private Sub ReportCriteria_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles Me.Loaded
        GeneralTasks.ChangeTheme(Me)

        Try
            'Me.parDateRange.Visible = False

            With Me.drpConsult
                '.ItemsSource = CType(Lookups.ConsultantList, IListSource).GetList
                .ItemsSource = CType(Lookups.ConsultantListBranchWise(GlobalCRM.CurrentConID), IListSource).GetList
                .DisplayMemberPath = "con_name"
                .SelectedValuePath = "con_id"
            End With

            With Me.drpDepart
                '.ItemsSource = CType(Lookups.BranchList, IListSource).GetList
                .ItemsSource = CType(Lookups.BranchList(GlobalCRM.CurrentConID), IListSource).GetList
                .DisplayMemberPath = "branch_name"
                .SelectedValuePath = "branch_id"
            End With

            With Me.drpDepart2
                '.ItemsSource = CType(Lookups.BranchList(True), IListSource).GetList
                .ItemsSource = CType(Lookups.BranchList(GlobalCRM.CurrentConID), IListSource).GetList
                .DisplayMemberPath = "branch_name"
                .SelectedValuePath = "branch_id"
            End With


            With Me.drpDateRange
                .ItemsSource = CType(Me.LoadDateRanges, IListSource).GetList
                .DisplayMemberPath = "rangename"
                .SelectedValuePath = "rangeid"
                Me.drpDateRange.SelectedIndex = 1
            End With

            With Me.lstProductTypes
                .ItemsSource = CType(Lookups.ProductTypes, IListSource).GetList
                .DisplayMemberPath = "producttype_name"
                .SelectedValuePath = "producttype_id"
            End With

            Me.HideTheCriteria()

            With Me.lstReports
                Dim dt As DataTable = Me.GetReportList()
                If dt.Rows.Count = 0 Then
                    MsgBox("List not built")
                    Exit Sub
                Else
                    .ItemsSource = dt
                    .Columns(0).IsVisible = False
                    '.Columns(1).Header = "Report Names"
                    .Columns(1).Width = New GridLength(290)
                    .Columns(2).IsVisible = False
                    .Columns(3).IsVisible = False
                    .Columns(4).IsVisible = False
                    .Columns(5).IsVisible = False
                    .Columns(6).IsVisible = False
                End If

            End With

            Me.CurrentRole = 1
            Me.Products = 1
            'Me.divSLA.Visible = False
            'Me.divClientType.Visible = False
            'Me.divProducts.Visible = False
            'Me.divConsult.Visible = False
            'Me.divDates.Visible = False

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "ReportCriteria-ReportCriteria_Loaded", False)
            Me.Close()
        End Try
    End Sub

    Private Function LoadDateRanges() As DataTable

        Dim DateRanges As New DataTable
        Dim i As Integer
        Dim Row As DataRow

        With DateRanges
            .Columns.Add(New DataColumn("rangeid", System.Type.GetType("System.Int16")))
            .Columns.Add(New DataColumn("rangename", System.Type.GetType("System.String")))
        End With

        For i = 1 To 16
            Row = DateRanges.NewRow
            Row.Item("rangeid") = i
            Row.Item("rangename") = (CType(i, DateRanges)).ToString.Replace("_", " ")
            DateRanges.Rows.Add(Row)
        Next

        Return DateRanges

    End Function

    Private Sub CheckConsultant() Handles radAll.Checked, radBranch.Checked, radConsultant.Checked
        If radAll.IsChecked = True Then
            Me.drpConsult.SelectedIndex = -1
            Me.drpDepart.SelectedIndex = -1
            Me.drpConsult.Visibility = Windows.Visibility.Hidden : Me.litConsult.Visibility = Windows.Visibility.Hidden
            Me.drpDepart.Visibility = Windows.Visibility.Hidden : Me.litDepart.Visibility = Windows.Visibility.Hidden

        ElseIf radConsultant.IsChecked = True Then
            Me.drpConsult.SelectedIndex = -1
            Me.drpDepart.SelectedIndex = -1
            Me.drpConsult.Visibility = Windows.Visibility.Visible : Me.litConsult.Visibility = Windows.Visibility.Visible
            Me.drpDepart.Visibility = Windows.Visibility.Hidden : Me.litDepart.Visibility = Windows.Visibility.Hidden

        ElseIf radBranch.IsChecked = True Then
            Me.drpConsult.SelectedIndex = -1
            Me.drpDepart.SelectedIndex = -1
            Me.drpConsult.Visibility = Windows.Visibility.Hidden : Me.litConsult.Visibility = Windows.Visibility.Hidden
            Me.drpDepart.Visibility = Windows.Visibility.Visible : Me.litDepart.Visibility = Windows.Visibility.Visible

        End If
    End Sub

    Private Sub CheckProductSelection() Handles radProdAll.Checked, radByBranch.Checked, radByProductType.Checked, radRetiredProducts.Checked
        If radProdAll.IsChecked = True Or radRetiredProducts.IsChecked = True Then
            Me.lstProductTypes.Visibility = Windows.Visibility.Hidden : Me.lblProductType.Visibility = Windows.Visibility.Hidden
            Me.drpDepart2.Visibility = Windows.Visibility.Hidden : Me.lblProductBranch.Visibility = Windows.Visibility.Hidden
            drpDepart2.SelectedIndex = -1
        ElseIf radByBranch.IsChecked = True Then
            Me.lstProductTypes.Visibility = Windows.Visibility.Hidden : Me.lblProductType.Visibility = Windows.Visibility.Hidden
            Me.drpDepart2.Visibility = Windows.Visibility.Visible : Me.lblProductBranch.Visibility = Windows.Visibility.Visible
            drpDepart2.SelectedIndex = -1
        ElseIf radByProductType.IsChecked = True Then
            Me.lstProductTypes.Visibility = Windows.Visibility.Visible : Me.lblProductType.Visibility = Windows.Visibility.Visible
            Me.drpDepart2.Visibility = Windows.Visibility.Hidden : Me.lblProductBranch.Visibility = Windows.Visibility.Hidden
            drpDepart2.SelectedIndex = -1
        End If
    End Sub

    Private Function GetReportList() As DataTable
        Dim ReportList As New DataTable
        Try
            Dim strReportListSchema As String = Assembly.GetExecutingAssembly.GetName().Name & ".ReportList.xsd"
            Dim singleton As Singleton = singleton.Instance
            Dim strReportList As String
            If (singleton.CurrentConSecurityLevel = SecurityLevel.AdminUser Or singleton.CurrentConSecurityLevel = SecurityLevel.BranchManager) Then
                strReportList = Assembly.GetExecutingAssembly.GetName().Name & ".ReportList.xml"
            Else
                strReportList = Assembly.GetExecutingAssembly.GetName().Name & ".ReportListForConsultants.xml"
            End If
            Dim streamXMLSchema As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(strReportListSchema)
            If Not streamXMLSchema Is Nothing Then
                ReportList.ReadXmlSchema(streamXMLSchema)
            Else
                MsgBox("Report Schema not loaded!")
            End If
            Dim streamXML As Stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(strReportList)
            If Not streamXML Is Nothing Then
                ReportList.ReadXml(streamXML)
            Else
                MsgBox("Report List not loaded!")
            End If

        Catch ex As UnauthorizedAccessException
            CommonFuncs.ErrorHandler(ex, "Unable to have access to the file!", False)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "ReportCriteria-GetReportList", False)
        End Try
        Return ReportList
    End Function


    Private Function GetDirectoryPermissions(ByVal user As String, ByVal domainName As String, ByVal folderPath As String) As FileSystemRights
        If Not (Directory.Exists(folderPath)) Then
            Return (0)
        End If

        Dim identityReference As String = (domainName + "\" + user).ToLower()
        Dim dirSecurity As DirectorySecurity = Directory.GetAccessControl(folderPath, AccessControlSections.Access)
        For Each fsRule As FileSystemAccessRule In dirSecurity.GetAccessRules(True, True, GetType(System.Security.Principal.NTAccount))

            If fsRule.IdentityReference.Value.ToLower() = identityReference Then
                Return (fsRule.FileSystemRights)
            End If

        Next
        Return (0)
    End Function

    ' Adds an ACL entry on the specified file for the specified account.
    Sub AddFileSecurity(ByVal fileName As String, ByVal account As String, _
        ByVal rights As FileSystemRights, ByVal controlType As AccessControlType)
        Try

            ' Get a FileSecurity object that represents the 
            ' current security settings.
            Dim fSecurity As FileSecurity = File.GetAccessControl(fileName)

            ' Add the FileSystemAccessRule to the security settings. 
            Dim accessRule As FileSystemAccessRule = _
                New FileSystemAccessRule(account, rights, controlType)

            fSecurity.AddAccessRule(accessRule)

            ' Set the new access settings.
            File.SetAccessControl(fileName, fSecurity)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "ReportCriteria-AddFileSecurity", False)
        End Try


    End Sub

    Sub AddDirectorySecurity(ByVal dirName As String, ByVal account As String, _
    ByVal rights As FileSystemRights, ByVal controlType As AccessControlType)
        Try
            ' Get a FileSecurity object that represents the 
            ' current security settings.
            Dim dSecurity As DirectorySecurity = Directory.GetAccessControl(dirName)

            ' Add the FileSystemAccessRule to the security settings. 
            Dim accessRule As FileSystemAccessRule = _
                New FileSystemAccessRule(account, rights, controlType)

            dSecurity.AddAccessRule(accessRule)

            ' Set the new access settings.
            Directory.SetAccessControl(dirName, dSecurity)
        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "ReportCriteria-AddDirectorySecurity", False)

        End Try


    End Sub


    'Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click
    '    Dim allTableNames As DataTable = CommonDataFunctions.GetSQLDatatable("SELECT table_name FROM INFORMATION_SCHEMA.TABLES")
    '    Dim dynamicString As New System.Text.StringBuilder
    '    Dim currentDatabase As String = CommonDataFunctions.GetSQLScalar("select db_name()")
    '    For Each currentRow As DataRow In allTableNames.Rows
    '        Dim currentIndexTable As DataTable = CommonDataFunctions.GetSQLDatatable("sp_helpindex " + currentRow(0).ToString())
    '        If currentIndexTable Is Nothing Then
    '            Continue For
    '        End If
    '        For Each currentIndex As DataRow In currentIndexTable.Rows
    '            If currentIndex(0).ToString().Contains(" ") Then
    '                dynamicString.Append("DBCC  INDEXDEFRAG(" + currentDatabase + "," + currentRow(0).ToString() + ",'" + currentIndex(0).ToString() + "')" + vbCrLf + " Go " + vbCrLf)
    '            Else
    '                dynamicString.Append("DBCC  INDEXDEFRAG(" + currentDatabase + "," + currentRow(0).ToString() + "," + currentIndex(0).ToString() + ")" + vbCrLf + " Go " + vbCrLf)
    '            End If
    '        Next
    '    Next
    '    Dim query As String = dynamicString.ToString()
    '    Try
    '        CommonDataFunctions.ExecuteSQL(query)
    '    Catch ex As Exception

    '    End Try

    'End Sub

    Private Sub drpDateRange_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles drpDateRange.SelectionChanged
        Me.ShowHideDateControls()
    End Sub

    Private Sub ShowHideDateControls()

        Select Case CType(Me.drpDateRange.SelectedValue, DateRanges)

            Case DateRanges.From_Date_To_Present, DateRanges.Select_Date

                Me.txtDateFrom.Visibility = Windows.Visibility.Visible
                'Me.imgTrigger1.Visible = True
                Me.LabelStart.Visibility = Windows.Visibility.Visible

                Me.txtDateTo.Visibility = Windows.Visibility.Hidden
                'Me.imgTrigger2.Visible = False
                Me.LabelEnd.Visibility = Windows.Visibility.Hidden


            Case DateRanges.Select_Range

                'Me.parDateRange.Visible = True

                Me.txtDateFrom.Visibility = Windows.Visibility.Visible
                'Me.imgTrigger1.Visible = True
                Me.LabelStart.Visibility = Windows.Visibility.Visible

                Me.txtDateTo.Visibility = Windows.Visibility.Visible
                'Me.imgTrigger2.Visible = True
                Me.LabelEnd.Visibility = Windows.Visibility.Visible

            Case Else

                'Me.parDateRange.Visible = False

                Me.txtDateFrom.Visibility = Windows.Visibility.Hidden
                'Me.imgTrigger1.Visible = False
                Me.LabelStart.Visibility = Windows.Visibility.Hidden

                Me.txtDateTo.Visibility = Windows.Visibility.Hidden
                'Me.imgTrigger2.Visible = False
                Me.LabelEnd.Visibility = Windows.Visibility.Hidden

        End Select


    End Sub

    Private Sub SelectRole() Handles radSoldBy.Checked, radCaseWorker.Checked
        If radSoldBy.IsChecked = True Then
            Me.CurrentRole = 1
        ElseIf radCaseWorker.IsChecked = True Then
            Me.CurrentRole = 2
        End If
    End Sub

    Private Sub ProductRole() Handles radProdAll.Checked, radByBranch.Checked, radRetiredProducts.Checked, radByProductType.Checked
        If radProdAll.IsChecked = True Then
            Me.Products = 1
        ElseIf radByBranch.IsChecked = True Then
            Me.Products = 2
        ElseIf radRetiredProducts.IsChecked = True Then
            Me.Products = 3
        ElseIf radByProductType.IsChecked = True Then
            Me.Products = 4
        End If
    End Sub

    Private Sub btnRunReport_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnRunReport.Click

        Dim Criteria As New Reports.ReportCriteria
        'If drpDateRange.SelectedIndex = -1 Then
        '    CommonFuncs.DisplayMessage("Please select the Range for which you want to run the report !", CommonDialog.CustomDialogIcons.Information, "")
        '    Exit Sub
        'End If
        Try
            With Criteria
                Dim singleton As Singleton = singleton.Instance
                .Consultant_Id = singleton.CurrentConId
                .Consultant_Name = singleton.CurrentConName
                If radConsultant.IsChecked = True Then
                    .Consultant_All = False
                    .Consultant_BranchId = 0
                    If drpConsult.SelectedIndex <> -1 Then
                        .Consultant_Id = Me.drpConsult.SelectedValue
                        .Consultant_Name = Me.drpConsult.Text 'Lookups.ConsultantName(.Consultant_Id)
                    Else
                        CommonFuncs.DisplayMessage("Please select the consultant for which you want to run the report !", CommonDialog.CustomDialogIcons.Information, "")
                        Exit Sub
                    End If

                ElseIf radAll.IsChecked = True Then
                    .Consultant_All = True
                    .Consultant_BranchId = 0
                    .Consultant_Id = 0
                    .Consultant_Name = "All Consultants"
                ElseIf radBranch.IsChecked = True Then
                    .Consultant_All = False
                    If drpDepart.SelectedIndex <> -1 Then
                        .Consultant_BranchId = Me.drpDepart.SelectedValue
                        .Consultant_Id = 0
                        .Consultant_Name = "All " & Me.drpDepart.Text & " Consultants"
                    Else
                        CommonFuncs.DisplayMessage("Please select the branch for which you want to run the report !", CommonDialog.CustomDialogIcons.Information, "")
                        Exit Sub
                    End If

                End If

                .Consultant_Role = Me.CurrentRole

                Select Case CType(Me.Products, ProductSelection)

                    Case ProductSelection.All
                        .Product_Selection = Reports.ProductSelection.All
                        .Product_Selection_Id = 0

                    Case ProductSelection.By_Department
                        .Product_Selection = Reports.ProductSelection.By_Department
                        If Me.drpDepart2.SelectedIndex <> -1 Then
                            .Product_Selection_Id = Me.drpDepart2.SelectedValue
                        Else
                            CommonFuncs.DisplayMessage("Please select the branch for which you want to run the report !", CommonDialog.CustomDialogIcons.Information, "")
                            Exit Sub
                        End If


                    Case ProductSelection.By_Product_Type

                        Dim IdList As String = ""
                        'Dim Li As ListItem

                        IdList = lstProductTypes.Text

                        'For Each Li In Me.lstProductTypes.Items
                        '    If Li.Selected Then
                        '        If IdList.Length > 0 Then
                        '            IdList = IdList & ","
                        '        End If
                        '        IdList = IdList & Li.Value
                        '    End If
                        'Next

                        .Product_Selection = Reports.ProductSelection.By_Product_Type
                        .Product_Selection_Id = IdList

                    Case ProductSelection.Retired_Products
                        .Product_Selection = Reports.ProductSelection.Retired_Products
                        .Product_Selection_Id = 0

                End Select

                '.StartDate = Request.Form(Me.txtDateFrom.UniqueID)
                '.EndDate = Request.Form(Me.txtDateTo.UniqueID)

                If txtDateFrom.Text = String.Empty Then
                    .StartDate = CommonDataFunctions.GetLocalServer 'DateTime.Now.ToString()
                    .StartDate = Format(CDate(.StartDate), "dd-MMM-yyyy")
                Else
                    .StartDate = Me.txtDateFrom.Text
                    .StartDate = Format(CDate(.StartDate), "dd-MMM-yyyy")
                End If
                If txtDateTo.Text = String.Empty Then
                    .EndDate = CommonDataFunctions.GetLocalServer 'DateTime.Now.ToString()
                    .EndDate = Format(CDate(.EndDate), "dd-MMM-yyyy")
                Else
                    .EndDate = Me.txtDateTo.Text
                    .EndDate = Format(CDate(.EndDate), "dd-MMM-yyyy")
                End If

                Me.GetDateRange(CType(Me.drpDateRange.SelectedValue, DateRanges), .StartDate, .EndDate)

                If Not .StartDate Is Nothing Then
                    If .EndDate = .StartDate Then
                        .Period = MonthName(CDate(.StartDate).Month) & " " & CDate(.StartDate).Year
                    Else
                        If CDate(.StartDate).Day = 1 And CDate(.EndDate).Day = DateTime.DaysInMonth(CDate(.StartDate).Year, CDate(.StartDate).Month) And CDate(.StartDate).Month = CDate(.EndDate).Month Then
                            .Period = MonthName(CDate(.StartDate).Month) & " " & CDate(.StartDate).Year
                        Else
                            .Period = Format(CDate(.StartDate), "dd-MMM-yyyy") & " to " & Format(CDate(.EndDate), "dd-MMM-yyyy")
                        End If
                    End If
                End If

                Select Case .Product_Selection
                    Case Reports.ProductSelection.All
                        .Product_Name = "All Products"
                    Case Reports.ProductSelection.By_Department
                        .Product_Name = Me.drpDepart2.SelectedItem.Text
                    Case Reports.ProductSelection.By_Product_Type
                        .Product_Name = "Multiple Product Types"
                    Case Reports.ProductSelection.Retired_Products
                        .Product_Name = "Retired Products"

                End Select


                '.Account_Types = CType(Me.radSLAAccounts.SelectedValue, Reports.AccountTypes)

                '.Client_Type = CType(Me.radClientType.SelectedValue, Reports.ClientTypes)


                .Account_Types = CType(1, Reports.AccountTypes)

                .Client_Type = CType(1, Reports.ClientTypes)

            End With

            Me.ReportCriteria = Criteria
            Dim PgSelection As Pageselection


            'Select Case Me.lstReports.SelectedIndex
            Dim reportName As String = Me.SelectedReportName
            Select Case reportName
                Case "Commission Report"
                    Me.CurrentReport = Reports.ReportType.Commission
                    PgSelection = Pageselection.CrystalPage
                Case "Invoice List by Consultant (202)"
                    Me.CurrentReport = Reports.ReportType.InvoiceList
                    PgSelection = Pageselection.CrystalPage
                Case "Invoice List V2 (204)"
                    Me.CurrentReport = Reports.ReportType.InvoiceListV2
                    PgSelection = Pageselection.CrystalPage
                Case "General Cash Up (200)"
                    Me.CurrentReport = Reports.ReportType.CashUp
                    PgSelection = Pageselection.CrystalPage
                Case "Event Summary by Consultant (302)"
                    Me.CurrentReport = Reports.ReportType.EventSummaryConsultant
                    PgSelection = Pageselection.CrystalPage
                Case "Price List (1)"
                    Me.CurrentReport = Reports.ReportType.PriceList
                    PgSelection = Pageselection.CrystalPage
                Case "Case Stages (10)"
                    Me.CurrentReport = Reports.ReportType.CaseStages
                    PgSelection = Pageselection.CrystalPage
                Case "Pipeline PreSale (100)"
                    Me.CurrentReport = Reports.ReportType.PipelinePreSale
                    PgSelection = Pageselection.CrystalPage
                Case "Sales Status Summary (101)"
                    Me.CurrentReport = Reports.ReportType.SalesStatusSummary
                    PgSelection = Pageselection.CrystalPage
                Case "Visas Expiring (108)"
                    Me.CurrentReport = Reports.ReportType.VisasExpiring
                    PgSelection = Pageselection.CrystalPage
                Case "Open Cases with No Invoice (113)"
                    Me.CurrentReport = Reports.ReportType.OpenCasesNoInvoice
                    PgSelection = Pageselection.CrystalPage
                Case "Entered by Summary (115)"
                    Me.CurrentReport = Reports.ReportType.EnteredBySummary
                    PgSelection = Pageselection.CrystalPage
                Case "Migration Case Stages (205)"
                    Me.CurrentReport = Reports.ReportType.MigrationCaseStages
                    PgSelection = Pageselection.CrystalPage
                Case "Leads per Consultant (220)"
                    Me.CurrentReport = Reports.ReportType.LeadsPerConsultant
                    PgSelection = Pageselection.CrystalPage
                Case "Web Leads per Day (221)"
                    Me.CurrentReport = Reports.ReportType.WebLeadsPerDay
                    PgSelection = Pageselection.CrystalPage
                Case "Web Sales per Day"
                    Me.CurrentReport = Reports.ReportType.WebSalesPerDay
                    PgSelection = Pageselection.CrystalPage
                Case "Web Leads Assigned To Salespeople"
                    Me.CurrentReport = Reports.ReportType.WebLeadsAssignedToSalespeople
                    PgSelection = Pageselection.CrystalPage
                Case "Conversion Report by Consultant"
                    Me.CurrentReport = Reports.ReportType.ConversionByConsultant
                    PgSelection = Pageselection.CrystalPage
                Case "Conversion Report by Products"
                    Me.CurrentReport = Reports.ReportType.ConversionRateProduct
                    PgSelection = Pageselection.CrystalPage
                Case "Write-Off List"
                    Me.CurrentReport = Reports.ReportType.WriteOffList
                    PgSelection = Pageselection.CrystalPage
                Case "Work In Progress(WIP)"
                    Me.CurrentReport = Reports.ReportType.WorkInProgress
                    PgSelection = Pageselection.CrystalPage
                Case "Cases With No Events"
                    Me.CurrentReport = Reports.ReportType.CaseWithNoEvents
                    PgSelection = Pageselection.CrystalPage
                Case "cases with overdue balance (after 90 days)"
                    Me.CurrentReport = Reports.ReportType.CaseWithOutstandingBalance90
                    PgSelection = Pageselection.CrystalPage
                Case "Sales Consultant / Caseworker Pipeline"
                    Me.CurrentReport = Reports.ReportType.UserPipeline
                    PgSelection = Pageselection.CrystalPage
                Case "Cases Submitted(Grouped by Case Worker)"
                    Me.CurrentReport = Reports.ReportType.CasesSubmitted
                    PgSelection = Pageselection.CrystalPage
                Case "Cases Assigned(Grouped by Case Worker)"
                    Me.CurrentReport = Reports.ReportType.CasesAssigned
                    PgSelection = Pageselection.CrystalPage
                Case "cases with overdue balance (after 60 days)"
                    Me.CurrentReport = Reports.ReportType.CaseWithOutstandingBalance60
                    PgSelection = Pageselection.CrystalPage
                Case "Feedback Report"
                    Me.CurrentReport = Reports.ReportType.FeedbackReport
                    PgSelection = Pageselection.GridPage
                    'Case 28
                    '    Me.CurrentReport = Reports.ReportType.DailySalesReport
                    '    PgSelection = Pageselection.CrystalPage
                    'Case 29
                    '    Me.CurrentReport = Reports.ReportType.WeeklySalesReport
                    '    PgSelection = Pageselection.CrystalPage
                    'Case 30
                    '    Me.CurrentReport = Reports.ReportType.MonthlySalesReport
                    '    PgSelection = Pageselection.CrystalPage
                Case "Leads By Product"
                    Me.CurrentReport = Reports.ReportType.LeadsReportByProduct
                    PgSelection = Pageselection.CrystalPage
                Case "Payment Due 30 Days(Private Individuals)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue30
                    PgSelection = Pageselection.CrystalPage
                Case "Payment Due 60 Days(Private Individuals)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue60
                    PgSelection = Pageselection.CrystalPage
                Case "Payment Due 90 Days(Private Individuals)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue90
                    PgSelection = Pageselection.CrystalPage
                Case "Feedback Report For Cancelled(Presale)"
                    Me.CurrentReport = Reports.ReportType.FeedbackCanReport
                    PgSelection = Pageselection.GridPage
                Case "Payment Due 30 Days(Company)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue30SLA
                    PgSelection = Pageselection.CrystalPage
                Case "Payment Due 60 Days(Company)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue60SLA
                    PgSelection = Pageselection.CrystalPage
                Case "Payment Due 90 Days(Company)"
                    Me.CurrentReport = Reports.ReportType.PaymentDue90SLA
                    PgSelection = Pageselection.CrystalPage
                Case "Refunds List"
                    Me.CurrentReport = Reports.ReportType.RefundsList
                    PgSelection = Pageselection.CrystalPage
                Case "CSM Case Stages"
                    Me.CurrentReport = Reports.ReportType.CSMCaseStage
                    PgSelection = Pageselection.CrystalPage
                Case "Invoice List by CaseId"
                    Me.CurrentReport = Reports.ReportType.InvoiceListCase
                    PgSelection = Pageselection.CrystalPage
                Case "Case Assigned to CSM"
                    Me.CurrentReport = Reports.ReportType.CaseAssignedCSM
                    PgSelection = Pageselection.CrystalPage
                Case "Leads By Product Type"
                    Me.CurrentReport = Reports.ReportType.LeadsProductType
                    PgSelection = Pageselection.CrystalPage
            End Select

            If PgSelection = Pageselection.GridPage Then
                'Response.Redirect("Gridreportviewer.aspx")
            ElseIf PgSelection = Pageselection.CrystalPage Then
                Dim frmViewer As New frmReportViewer
                frmViewer.Show()
                'Me.HideTheCriteria()
                'Dim myNav As NavigationService
                'myNav = NavigationService.GetNavigationService(Me)
                'myNav.Navigate(New System.Uri("/Report Forms/frmReportViewer.xaml", UriKind.Relative))
                ''Response.Redirect("reportviewer.aspx")
            End If

        Catch ex As Exception
            CommonFuncs.ErrorHandler(ex, "ReportCriteria-btnRunReport", False)
        Finally
            lstReports.SelectedItem = Nothing
        End Try

    End Sub

    Private Sub SetSelectedRowIndex()
        Dim sReportIndex As Integer = 0
        Dim sReportName As String = String.Empty
        Dim dataReports As DataTable = Me.lstReports.ItemsSource
        Dim selectedReportRow As DataRow = Me.lstReports.SelectedItem
        For currentRowIndex As Integer = 0 To dataReports.Rows.Count - 1
            Dim currentRow As DataRow = dataReports.Rows(currentRowIndex)
            If currentRow(0).ToString() = selectedReportRow(0).ToString() Then
                sReportIndex = currentRowIndex
                sReportName = selectedReportRow(1).ToString()
                Exit For
            End If
        Next
        Me.SelectedReportIndex = sReportIndex
        Me.SelectedReportName = sReportName
    End Sub

    Private Sub GetDateRange(ByVal RangeId As DateRanges, ByRef StartDate As String, ByRef EndDate As String)

        Select Case RangeId
            Case DateRanges.All

                'No SQL required

            Case DateRanges.Today

                StartDate = Format(Now, "dd-MMM-yyyy") & " 00:00:00"
                EndDate = Format(Now, "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.Select_Date

                StartDate = Format(CDate(StartDate), "dd-MMM-yyyy") & " 00:00:00"
                EndDate = Format(CDate(StartDate), "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.Select_Range

                StartDate = Format(CDate(StartDate), "dd-MMM-yyyy") & " 00:00:00"
                EndDate = Format(CDate(EndDate), "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.This_Week

                StartDate = CStr(Format(CDate(Now.AddDays(-Weekday(Now, DayOfWeek.Sunday))), "dd-MMM-yyyy")) & " 23:59:59"
                EndDate = CStr(Format(CDate(Now.AddDays(-Weekday(Now, DayOfWeek.Sunday))).AddDays(7), "dd-MMM-yyyy")) & " 00:00:00" '(Format(CDate(EndDate), "dd-MMM-yyyy")) & " 23:59:59"

            Case DateRanges.This_Month

                StartDate = "01-" & MonthName(Now.Month, True) & "-" & Now.Year & " 00:00:00"
                EndDate = Format(CDate(Now), "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.Last_Week

                StartDate = CStr(Format(CDate(Now.AddDays(-Weekday(Now, DayOfWeek.Sunday) - 7)), "dd-MMM-yyyy")) & " 23:59:59"
                EndDate = CStr(Format(CDate(Now.AddDays(-Weekday(Now, DayOfWeek.Sunday))), "dd-MMM-yyyy")) & " 23:59:00"

            Case DateRanges.Last_Month

                StartDate = "01-" & MonthName(Now.AddMonths(-1).Month, True) & "-" & IIf(Now.Month <> 1, Now.Year, Now.Year - 1) & " 00:00:00"
                EndDate = DateTime.DaysInMonth(Now.AddMonths(-1).Year, Now.AddMonths(-1).Month) & "-" & MonthName(Now.AddMonths(-1).Month, True) & "-" & IIf(Now.Month <> 1, Now.Year, Now.Year - 1) & " 23:59:59"

            Case DateRanges.Yesterday

                StartDate = Format(Now.AddDays(-1), "dd-MMM-yyyy") & " 00:00:00"
                EndDate = Format(Now.AddDays(-1), "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.This_Month_Last_Year

                StartDate = "01-" & MonthName(Now.Month, True) & "-" & Now.AddYears(-1).Year & " 00:00:00"
                EndDate = DateTime.DaysInMonth(Now.AddYears(-1).Year, Now.AddYears(-1).Month) & "-" & MonthName(Now.Month, True) & "-" & Now.AddYears(-1).Year & " 23:59:59"

            Case DateRanges.Last_Month_Last_Year

                StartDate = "01-" & MonthName(Now.AddMonths(-1).Month, True) & "-" & Now.AddYears(-1).Year & " 00:00:00"
                EndDate = DateTime.DaysInMonth(Now.AddYears(-1).Year, Now.AddYears(-1).AddMonths(-1).Month) & "-" & MonthName(Now.AddMonths(-1).Month, True) & "-" & Now.AddYears(-1).Year & " 23:59:59"

            Case DateRanges.Year_To_Date

                StartDate = "01-Jan-" & Now.Year & " 00:00:00"
                EndDate = Format(Now, "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.Last_Year

                StartDate = "01-Jan-" & Now.AddYears(-1).Year & " 00:00:00"
                EndDate = "31-Dec-" & Now.AddYears(-1).Year & " 23:59:59"

            Case DateRanges.Financial_Year_To_Date

                If Now < CDate("31-Mar-" & Now.Year & " 23:59:59") Then
                    StartDate = "01-Apr-" & Now.AddYears(-1).Year & " 00:00:00"
                Else
                    StartDate = "01-Apr-" & Now.Year & " 00:00:00"
                End If

                EndDate = Format(Now, "dd-MMM-yyyy") & " 23:59:59"

            Case DateRanges.Last_Financial_Year

                If Now < CDate("31-Mar-" & Now.Year & " 23:59:59") Then
                    StartDate = "01-Apr-" & Now.AddYears(-2).Year & " 00:00:00"
                Else
                    StartDate = "01-Apr-" & Now.AddYears(-1).Year & " 00:00:00"
                End If

                If Now < CDate("31-Mar-" & Now.Year & " 23:59:59") Then
                    EndDate = "31-Mar-" & Now.AddYears(-1).Year & " 23:59:59"
                Else
                    EndDate = "31-Mar-" & Now.Year & " 23:59:59"
                End If

            Case DateRanges.From_Date_To_Present

                StartDate = Format(CDate(StartDate), "dd-MMM-yyyy") & " 00:00:00"
                EndDate = Format(Now, "dd-MMM-yyyy") & " 23:59:59"


        End Select

    End Sub

    Private Sub lstReports_SelectionChanged(ByVal sender As Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs) Handles lstReports.SelectionChanged
        Dim currentRow As DataRow = Me.lstReports.SelectedItem
        If Not currentRow Is Nothing Then
            'For currentIndex As Integer = 0 To currentRow.ItemArray.Count - 1
            '    MsgBox(currentRow(currentIndex).ToString())
            'Next
            Me.SetSelectedRowIndex()
            If currentRow("criteria_date").ToString = "1" Then
                grpDates.Visibility = Windows.Visibility.Visible
            Else
                grpDates.Visibility = Windows.Visibility.Hidden
            End If
            Dim singleton As Singleton = singleton.Instance
            If (singleton.CurrentConSecurityLevel = SecurityLevel.AdminUser Or singleton.CurrentConSecurityLevel = SecurityLevel.BranchManager) Then
                If currentRow("criteria_consultant").ToString = "1" Then
                    grpConsultants.Visibility = Windows.Visibility.Visible
                Else
                    grpConsultants.Visibility = Windows.Visibility.Hidden
                End If

                If currentRow("criteria_product").ToString = "1" Then
                    grpProducts.Visibility = Windows.Visibility.Visible
                Else
                    grpProducts.Visibility = Windows.Visibility.Hidden
                End If
            End If
            Me.ClearControls()
        End If
    End Sub

    Private Sub HideTheCriteria()

        Me.drpConsult.Visibility = Windows.Visibility.Hidden : Me.litConsult.Visibility = Windows.Visibility.Hidden
        Me.drpDepart.Visibility = Windows.Visibility.Hidden : Me.litDepart.Visibility = Windows.Visibility.Hidden

        Me.lstProductTypes.Visibility = Windows.Visibility.Hidden : Me.lblProductType.Visibility = Windows.Visibility.Hidden
        Me.drpDepart2.Visibility = Windows.Visibility.Hidden : Me.lblProductBranch.Visibility = Windows.Visibility.Hidden

        Me.LabelStart.Visibility = Windows.Visibility.Hidden : Me.txtDateFrom.Visibility = Windows.Visibility.Hidden
        Me.LabelEnd.Visibility = Windows.Visibility.Hidden : Me.txtDateTo.Visibility = Windows.Visibility.Hidden

        Me.grpConsultants.Visibility = Windows.Visibility.Hidden
        Me.grpDates.Visibility = Windows.Visibility.Hidden
        Me.grpProducts.Visibility = Windows.Visibility.Hidden
        Me.ClearControls()
    End Sub

    Private Sub ClearControls()
        Me.drpConsult.SelectedIndex = -1
        Me.drpDateRange.SelectedIndex = -1
        Me.drpDepart.SelectedIndex = -1
        Me.drpDepart2.SelectedIndex = -1
        Me.radAll.IsChecked = False
        Me.radBranch.IsChecked = False
        Me.radByBranch.IsChecked = False
        Me.radByProductType.IsChecked = False
        Me.radCaseWorker.IsChecked = False
        Me.radConsultant.IsChecked = False
        Me.radProdAll.IsChecked = False
        Me.radRetiredProducts.IsChecked = False
        Me.radSoldBy.IsChecked = False
        Me.lstReports.SelectedItem = Nothing
    End Sub

    Private Sub btnReport_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReport.Click

        Me.HideTheCriteria()

    End Sub

End Class
